package com.scs.application.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

/**
 * @Description:
 */
@Slf4j
public class SpringHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringHolder.applicationContext;
    }

    public static <T> T getBean(Class<T> cls) {
        try {
            return applicationContext.getBean(cls);
        } catch (BeansException e) {
            log.error("Get bean of " + cls.getName() + " failed.", e);
            return null;
        }
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }
}

